<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import {
  // createTableDataApi,
  MycreateTableDataApi,
  deleteTableDataApi,
  updateTableDataApi,
  // getTableDataApi,
  MygetTableDataApi,
  sendEmailCodeApi
} from "@/api/table"
import { type GetTableData, type MyGetTableData } from "@/api/table/types/table"
import { type FormInstance, type FormRules, ElMessage, ElMessageBox } from "element-plus"
import { Search, Refresh, CirclePlus, Delete, Download, RefreshRight } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import { encrypt } from "@/utils/rsa"

defineOptions({
  // 命名当前组件
  name: "PeopleManagPermission"
})

const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

// const totalTime = 0 // 倒计时时间
const countingDown = ref(false) // 倒计时状态

// 倒计时剩余时间
const remainingTime = reactive({
  seconds: 0
})

// 计时器变量
let timer: NodeJS.Timeout | null = null
// 倒计时停止
const stopCountingDown = () => {
  if (timer) {
    clearInterval(timer)
    timer = null
    countingDown.value = false
  }
}

//#region 增
const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = reactive({
  username: "",
  password: "",
  confirmPassword: "",
  role: "1",
  email: "",
  code: "",
  sex: "1"
})

const checkEmail = (my_email: string) => {
  const regEmail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
  if (regEmail.test(my_email)) {
    //合法的邮箱
    return true
  }
  return false
}

const sendCode = () => {
  const my_email = formData.email
  //邮箱校验不通过
  if (!checkEmail(my_email)) {
    ElMessage.error("请输入正确的邮箱")
    formData.email = ""
    return
  }

  sendEmailCodeApi(my_email)
    .then((res) => {
      ElMessage.success(res.message)
      if (!countingDown.value) {
        countingDown.value = true
        remainingTime.seconds = 60
      }
      timer = setInterval(() => {
        if (remainingTime.seconds > 0) {
          remainingTime.seconds--
        } else {
          stopCountingDown()
        }
      }, 1000)
    })
    .catch((e) => {
      timer = null
      countingDown.value = false
      remainingTime.seconds = 0
      ElMessage.error(e.message)
    })
}

const formRules: FormRules = reactive({
  username: [
    { required: true, trigger: "blur", message: "请输入用户名" },
    { min: 2, max: 10, message: "长度在 2 到 5 个字符", trigger: "blur" }
  ],
  password: [
    { required: true, trigger: "blur", message: "请输入密码" },
    {
      min: 3,
      max: 20,
      message: "长度在 3 到 20 个字符",
      trigger: "blur"
    }
  ],
  confirmPassword: [
    { required: true, message: "请输入确认密码", trigger: "blur" },
    {
      min: 3,
      max: 20,
      message: "长度在 3 到 20 个字符",
      trigger: "blur"
    }
  ],

  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    {
      type: "email",
      min: 9,
      max: 18,
      message: "邮箱格式错误",
      trigger: "blur"
    }
  ],
  code: [{ required: true, trigger: "blur", message: "请输入验证码" }],
  sex: [{ required: true, trigger: "blur", message: "请选择性别" }],
  role: [{ required: true, trigger: "blur", message: "请选择权限" }]
})

const handleCreate = () => {
  formRef.value?.validate((valid: boolean, fields) => {
    if (valid) {
      if (formData.password != formData.confirmPassword) {
        ElMessage.error("两次输入的密码不一致")
        formData.confirmPassword = ""
        formData.password = ""
        return
      }
      formData.password = encrypt(formData.password)
      formData.role = "normal"
      formData.sex = formData.sex == "1" ? 1 : 0
      console.log(formData)
      console.log(currentUpdateId.value)
      if (currentUpdateId.value === undefined) {
        MycreateTableDataApi(formData)
          .then(() => {
            ElMessage.success("新增成功")
            getTableData()
          })
          .finally(() => {
            dialogVisible.value = false
          })
      } else {
        updateTableDataApi({
          id: currentUpdateId.value,
          username: formData.username
        })
          .then(() => {
            ElMessage.success("修改成功")
            getTableData()
          })
          .finally(() => {
            dialogVisible.value = false
          })
      }
      // MycreateTableDataApi(formData)
      //   .then(() => {
      //     ElMessage.success("新增成功")
      //     dialogVisible.value = false
      //     // getTableData()
      //   })
      //   .catch((e) => {
      //     ElMessage.error(e.message)
      //   })
      // .finally(() => {
      //   dialogVisible.value = false
      // })
    } else {
      console.error("表单校验不通过", fields)
    }
  })
}

const resetForm = () => {
  currentUpdateId.value = undefined
  formData.username = ""
  formData.password = ""
  formData.confirmPassword = ""
  formData.role = "1"
  formData.email = ""
  formData.code = ""
  formData.sex = "1"
}
//#endregion

//#region 删
const handleDelete = (row: GetTableData) => {
  ElMessageBox.confirm(`正在删除用户：${row.username}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteTableDataApi(row.id).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  })
}
//#endregion

//#region 改
const currentUpdateId = ref<undefined | string>(undefined)
const handleUpdate = (row: MyGetTableData) => {
  currentUpdateId.value = row.infoId
  formData.username = row.infoUsername
  dialogVisible.value = true
}

const handCancel = () => {
  dialogVisible.value = false
}
//#endregion

//#region 查
const MytableData = ref<MyGetTableData[]>([])

const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  username: "",
  phone: ""
})

const MysearchData = reactive({
  username: "",
  email: ""
})

const getTableData = () => {
  loading.value = true
  MygetTableDataApi({
    currentPage: paginationData.currentPage,
    size: paginationData.pageSize,
    username: MysearchData.username || undefined,
    email: MysearchData.email || undefined
  })
    .then((res) => {
      paginationData.total = res.data.length
      for (let i = 0; i < paginationData.total; i++) {
        res.data[i]["infoSex"] = res.data[i]["infoSex"] == 1 ? "男" : "女"
      }
      MytableData.value = res.data

      console.log(MytableData.value)
    })
    .catch(() => {
      MytableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
const handleSearch = () => {
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  handleSearch()
}
//#endregion

/** 监听分页参数的变化 */
// immediate:用来设置是否立即回调 在这里设置为false
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="username" label="用户名">
          <el-input v-model="searchData.username" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="phone" label="邮箱">
          <el-input v-model="searchData.phone" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" :icon="CirclePlus" @click="dialogVisible = true">新增用户</el-button>
          <el-button type="danger" :icon="Delete">批量删除</el-button>
        </div>
        <div>
          <!-- <el-tooltip content="下载">
            <el-button type="primary" :icon="Download" circle />
          </el-tooltip> -->
          <el-tooltip content="刷新当前页">
            <el-button type="primary" :icon="RefreshRight" circle @click="getTableData" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="MytableData">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="infoId" label="用户序号" align="center" />
          <el-table-column prop="infoUsername" label="用户名" align="center" />
          <el-table-column prop="infoRole" label="角色" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.infoRole === 'normal'" effect="plain">normal</el-tag>
              <el-tag v-else type="warning" effect="plain">{{ scope.row.role }}</el-tag>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="phone" label="手机号" align="center" /> -->
          <el-table-column prop="infoEmail" label="邮箱" align="center" />
          <el-table-column prop="infoSex" label="性别" align="center" />
          <!-- <el-table-column prop="status" label="状态" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.status" type="success" effect="plain">启用</el-tag>
              <el-tag v-else type="danger" effect="plain">禁用</el-tag>
            </template>
          </el-table-column> -->
          <!-- <el-table-column prop="createTime" label="创建时间" align="center" /> -->
          <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog
      v-model="dialogVisible"
      :title="currentUpdateId === undefined ? '新增用户' : '修改用户'"
      @close="resetForm"
      width="30%"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
        <el-form-item prop="username" label="用户名">
          <el-input v-model="formData.username" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="password" label="密码" v-if="currentUpdateId === undefined">
          <el-input v-model="formData.password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item prop="confirmPassword" label="确认密码" v-if="currentUpdateId === undefined">
          <el-input v-model="formData.confirmPassword" placeholder="请输入确认密码" show-password />
        </el-form-item>
        <el-form-item prop="email" label="邮箱" v-if="currentUpdateId === undefined">
          <el-input v-model="formData.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item prop="code" label="验证码" v-if="currentUpdateId === undefined">
          <div style="display: inline-flex; align-items: center">
            <el-input v-model="formData.code" placeholder="请输入验证码" v-if="currentUpdateId === undefined" />
            <el-button
              @click="sendCode"
              :disabled="countingDown || remainingTime.seconds > 0"
              style="margin-left: 10px"
              >{{ countingDown ? `${remainingTime.seconds}秒后重试` : "发送验证码" }}</el-button
            >
          </div>
        </el-form-item>
        <el-form-item prop="role" label="用户权限" v-if="currentUpdateId === undefined">
          <el-radio-group v-model="formData.role" class="ml-4">
            <el-radio label="1" size="large">普通管理员</el-radio>
            <!-- <el-radio label="2" size="large">女</el-radio> -->
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="sex" label="性别" v-if="currentUpdateId === undefined">
          <el-radio-group v-model="formData.sex" class="ml-4">
            <el-radio label="1" size="large">男</el-radio>
            <el-radio label="0" size="large">女</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handCancel">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>
